package prime;

public class PrimeAlgorithm {
    public static void main(String[] args) {
        char[] data = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
        int size = data.length;
        int[][] weight = {
                {10000, 5, 7, 10000, 10000, 10000, 2},
                {1, 10000, 10000, 8, 10000, 10000, 11},
                {2, 10000, 10000, 10000, 13, 10000, 10000},
                {10000, 9, 10000, 10000, 10000, 4, 10000},
                {10000, 10000, 8, 10000, 10000, 5, 4},
                {10000, 10000, 10000, 4, 5, 10000, 6},
                {2, 3, 10000, 10000, 4, 6, 10000},
        };
        MinTree minTree = new MinTree();
        MGraph mGraph = new MGraph(size);
        minTree.createMinTree(mGraph, size, data, weight);
        minTree.prime(mGraph, 0);
    }
}

class MinTree {
    public void createMinTree(MGraph mGraph, int size, char[] data, int[][] weight) {
        for (int i = 0; i < size; i++) {
            mGraph.data[i] = data[i];
            for (int j = 0; j < size; j++) {
                mGraph.weight[i][j] = weight[i][j];
            }
        }

    }

    public void showMinTree(MGraph mGraph) {
        int size = mGraph.size;
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                System.out.print(mGraph.weight[i][j] + " ");
            }
            System.out.println();
        }
    }

    /**
     * 普利姆算法
     *
     * @param mGraph 图
     * @param index  表示从那个顶点开始找
     */
    public void prime(MGraph mGraph, int index) {
        //记录顶点是否被访问过
        int[] visited = new int[mGraph.size];
        visited[index] = 1;

        //一共需要遍历mGraph.size - 1次
        for (int i = 0; i < mGraph.size - 1; i++) {
            int min = 10000;
            int h1 = -1;
            int h2 = -1;//用于打印记录选择了哪个节点
            //内部开始找已经访问过的节点和未访问过的节点之间的最小值
            for (int j = 0; j < mGraph.size; j++) {
                if (visited[j] == 1) {//i 找的是已经访问过的节点
                    for (int k = 0; k < mGraph.size; k++) {
                        if ((visited[k] == 0) && (mGraph.weight[j][k] < min)) {
                            min = mGraph.weight[j][k];
                            h1 = j;
                            h2 = k;

                        }
                    }
                }
            }
            visited[h2] = 1;
            System.out.print(mGraph.data[h1] + "-->" + mGraph.data[h2]);
            System.out.println("权重为：" + min);

        }
    }
}

class MGraph {
    int size;
    char[] data;
    int[][] weight;

    public MGraph(int size) {
        this.size = size;
        data = new char[size];
        weight = new int[size][size];
    }
}
